#include "image.h"

bool loadImage(const char *filename, GLuint *tex)
{
	SDL_Surface *surface = NULL, *optimized = NULL;
	int numColors;
	GLenum colorFormat;

	surface = IMG_Load(filename);

	if (surface == NULL)
		return false;

	optimized = SDL_DisplayFormat(surface);

	numColors = optimized->format->BytesPerPixel;

	if (numColors == 4)
	{
		colorFormat = ((optimized->format->Rmask == 0x000000ff) ? GL_RGBA : GL_BGRA);
	}

	else if (numColors == 3)
	{
		colorFormat = ((optimized->format->Rmask == 0x000000ff) ? GL_RGB : GL_BGR);
	}

	glGenTextures(1, tex);
	glBindTexture(GL_TEXTURE_2D, *tex);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexImage2D( GL_TEXTURE_2D, 0, numColors, optimized->w, optimized->h, 0,
		colorFormat, GL_UNSIGNED_BYTE, optimized->pixels );

	SDL_FreeSurface(surface);
	SDL_FreeSurface(optimized);

	return true;
}